let domTRarr = [];
let nodeActive = null;
let currentSeleRow = 0;
let resData = null;
$NG.AllReady(function (
    page,
    { useDataIndexChange, useUpdateRow, useUpdateRows, useValuesChange, useClick }
) {
    // 编辑页面逻辑
    const mstform = $NG.getCmpApi("p_form_owner_rec_apply_m");
    const grid1 = $NG.getCmpApi("p_form_owner_rec_apply_d1");
    const grid2 = $NG.getCmpApi("p_form_owner_rec_apply_d2");
    const grid3 = $NG.getCmpApi("p_form_owner_rec_apply_d3");
    const grid4 = $NG.getCmpApi("p_form_owner_rec_apply_d4");

    // u_dept;
    var dtoolbar1 = $NG.getCmpApi("toolbar_p_form_owner_rec_apply_d1");
    dtoolbar1.insert({
        id: "add",
        text: "物料信息",
        iconCls: "icon-New",
    });
    useClick(async function ({ args }) {
        planadd();
    }, "add");
    function planadd() {
        $NG.external
            .openNGHelp({
                type: "NGMultipleHelp", //NGMultipleHelp
                helpId: "itemdataIdToNo", //帮助id
                valueField: "phid",
                labelField: "u_milestone_name", //显示字段
                // clientSqlFilter: {
                // 	bill_no: mstform.getValues().u_rkdbm_EXName,
                // 	phid_transno: 1,
                // },
            })
            .then((data) => {
                //根据字段名称新增引入每一行
                console.log(data, "data111111");
                try {
                    if (Array.isArray(data) && data.length > 0) {
                        var gridArr = [];
                        for (var i = 0; i < data.length; i++) {
                            console.log(data[i], "row1数据");
                            var gridObj = {};
                            //资源品类
                            gridObj.u_wl_no = data[i].origin.PhId;
                            gridObj.u_wl_no_EXName = data[i].origin.ItemNo;
                            gridObj.u_wl_name = data[i].origin.ItemName;
                            gridArr.push(gridObj);
                        }

                        console.log("planadd gridArr:");
                        console.log(gridArr);
                        grid1.addRows(gridArr);
                        grid1.refreshView();
                    } else {
                        console.error("返回的数据无效或为空:", data);
                    }
                } catch (error) {
                    console.error("处理数据时出错:", error);
                }
            })
            .catch((error) => {
                console.error("打开NGHelp时发生错误:", error);
            });
    }
    //表头字段变化逻辑BEGIN
    useValuesChange(({ args }) => {
        //监听来往单位名称
        console.log(args, "单位名称");

        //监听单位名称
        $NG.execServer(
            "fbsrdxx",
            { phid: args[0].u_unit_name.origin.phid },
            function (res) {
                const datas = JSON.parse(res.data)[0].extendObjects;
                console.log(datas, "data11111s");

                if (datas.region_id) {
                    console.log(datas.region_id, "datas.region_id");
                    $NG.execServer("getAddressToId", { phid: datas.region_id }, function (res2) {
                        const data2 = JSON.parse(res2.data)[0].extendObjects; //单返回值
                        console.log(data2, "data2");
                        $NG.updateState((updater) => {
                            updater.data.p_form_owner_rec_apply_m.setProps({
                                u_nation: {
                                    value: data2.nationno,
                                    label: data2.nationname,
                                },
                                u_province: {
                                    value: data2.provinceno,
                                    label: data2.provincename,
                                },
                                u_city: {
                                    value: data2.cityno,
                                    label: data2.cityname,
                                },
                                u_region: {
                                    value: data2.regionno,
                                    label: data2.regionname,
                                },
                                u_xxdz:datas.detail_add
                            });
                        });
                    });
                }
                //功能扩展
                $NG.execServer(
                    "searchIDBank",
                    { phid: datas.taxbank_id },
                    function (res1) {
                        const data = JSON.parse(res1.data)[0].extendObjects; //单返回值
                        console.log(data, "data");
                        $NG.updateState((updater) => {
                            updater.data.p_form_owner_rec_apply_m.setProps({
                                u_swyh: {
                                    value: data.phid,
                                    label: data.bankno,
                                }, //税务银行行号11
                            });
                        });
                    }
                );

                $NG.updateState((updater) => {
                    updater.data.p_form_owner_rec_apply_m.setProps({
                        // u_contacts: datas.linkman, //联系人
                        // u_contacts_phone: datas.phone, //联系电话
                        // u_name1: datas.compname, //
                        u_unit_no: args[0].u_unit_name.origin.compno,
                        u_id_card: datas.iden_card_id, //法人身份证身份证
                        u_nssflx: datas.taxpayertype, //纳税身份类型11
                        u_nsr_name: datas.tax_person, //纳税人姓名11

                        u_swdjdz: datas.tax_register_addr, //税务地址名称11
                        u_swyhmc: datas.taxbank_name, //税务银行名称11
                        u_swdjh: datas.taxaccount_no, //税务登记账号11(税务登记账号)
                        u_swdjdh: datas.phone, //税务登记电话
                        u_tyshxydm: datas.three_to_one, //社会信用代码11(社会信用代码)
                        u_zcsj: datas.regdate, //成立日期11
                        u_rygm: datas.firm_size, //公司规模11
                        // u_yz_name: datas.psn, //法人11()
                        u_zczj: datas.reg_fund, //注册资本11
                    });
                });
                console.log(datas.taxbank_id, "datas.taxbank_id");
            }
        );
    }, "p_form_owner_rec_apply_m.u_unit_name");

    useValuesChange(({ args }) => {
        console.log(mstform.getValues().u_lx);
        if (mstform.getValues().u_lx == 2) {
            if (mstform.getValues().phid_pc) {
                return;
            }
            $NG.alert("请先选择工程项目");
            mstform.getItem("u_lx").setValue({ code: "", name: "" });
        }
    }, "p_form_owner_rec_apply_m.u_lx"); //表头选择u_region字段
    useValuesChange(({ args }) => {
        console.log(mstform.getValues().u_lx);
        $NG.execServer(
            "projectSjbm",
            { phid: mstform.getItem("phid_pc").getValue() },
            function (res) {
                const datas = JSON.parse(res.data)[0].extendObjects;
                console.log(res, "resprojectSjbm");
                $NG.updateState((updater) => {
                    updater.data.p_form_owner_rec_apply_m.setProps({
                        u_sj_no: datas.user_sjbm, //项目编码
                        u_sj_name: datas.user_sjmc, //项目名称
                    });
                });
                //searchYZTosjhsjbm
                if (datas.user_sjbm && datas.user_sjmc) {
                    //通过商机编码和名称查询业主名称
                    $NG.execServer(
                        "YZTosjhsjbm",
                        {
                            sjname: datas.user_sjmc,
                            sjno: datas.user_sjbm,
                        },
                        function (res) {
                            try {
                                let YZData = JSON.parse(res.data)[0].extendObjects;
                                console.log(YZData.u_yz_name, "YZData");
                                $NG.updateState((updater) => {
                                    updater.data.p_form_owner_rec_apply_m.setProps({
                                        u_yz_name: YZData.u_yz_name, //业主名称
                                    });
                                });
                            } catch (error) { }
                        }
                    );
                }
            }
        );

        if (mstform.getValues().u_lx == 2) {
            if (mstform.getValues().phid_pc) {
                return;
            }
            $NG.alert("请先选择工程项目");
            mstform.getItem("u_lx").setValue({ code: "", name: "" });
        }
    }, "p_form_owner_rec_apply_m.phid_pc"); //表头选择u_region字段

    useValuesChange(({ args }) => {
        console.log(args.value);
        mstform.getItem("u_region").setValue(""); //表头选择u_product_line字段
        mstform.getItem("u_city").setValue(""); //表头选择u_product_line字段
        $NG.updateUI((updater) => {
            updater.fieldSetForm.p_form_owner_rec_apply_m.u_city.setProps({
                clientSqlFilter: { provinceno: mstform.getValues()?.u_province },
            });
            updater.fieldSetForm.p_form_owner_rec_apply_m.u_region.setProps({
                clientSqlFilter: { cityno: mstform.getValues()?.u_city },
            });
        });
    }, "p_form_owner_rec_apply_m.u_province"); //表头选择u_province字段
    useValuesChange(({ args }) => {
        mstform.getItem("u_region").setValue(""); //表头选择u_product_line字段
        $NG.updateUI((updater) => {
            updater.fieldSetForm.p_form_owner_rec_apply_m.u_city.setProps({
                clientSqlFilter: { provinceno: mstform.getValues()?.u_province },
            });
            updater.fieldSetForm.p_form_owner_rec_apply_m.u_region.setProps({
                clientSqlFilter: { cityno: mstform.getValues()?.u_city },
            });
        });
    }, "p_form_owner_rec_apply_m.u_city"); //表头选择u_city字段
    useValuesChange(({ args }) => {
        console.log(args.value);
        $NG.updateUI((updater) => {
            updater.fieldSetForm.p_form_owner_rec_apply_m.u_city.setProps({
                clientSqlFilter: { provinceno: mstform.getValues()?.u_province },
            });
            updater.fieldSetForm.p_form_owner_rec_apply_m.u_region.setProps({
                clientSqlFilter: { cityno: mstform.getValues()?.u_city },
            });
        });
    }, "p_form_owner_rec_apply_m.u_region"); //表头选择u_region字段



    useUpdateRows(({ args }) => {
        const rows = args[0];
        console.log(rows);
        if (mstform.getItem("u_sj_no").getValue() && mstform.getItem("u_dwsx").getValue()) {
            // if () {
            //     $NG.updateUI((updater, state) => {
            //         updater.fieldSetForm.p_form_visa_f_regist_d.u_cnt_name.setProps((e) => ({
            //             ...e,
            //             editor: {
            //                 ...e.editor,
            //                 required: true,
            //                 clientSqlFilter: {
            //                     phid_pc: `${mstform.getItem("phid_pc").getValue()}`,
            //                     bill_type: 1,
            //                 },
            //             },
            //         }));
            //     });
            // }
        } else {
            if (args[0].length > 0) {
                $NG.alert("请先补充商机号,推荐供应商");
                grid1.clearRows(); //先清空明细
            }
        }


        rows.forEach((row) => {
            //计算损失率
            row.u_ssl = (Number(((Number(row.u_vat_prc) || 0) -(Number(row.u_sc_prc) || 0)) / (Number(row.u_sc_prc) || 0)) || 0).toFixed(4)
            console.log(row.u_wl_name, "row");
            if (row.u_wl_no && mstform.getItem("u_sj_no").getValue() && mstform.getItem("u_dwsx").getValue()) {
                $NG.execServer(
                    "getHsdjToYztj",
                    {
                        '@sjbm': mstform.getItem("u_sj_no").getValue(),
                        '@itemno': row.u_wl_no,
                        '@dwmc': mstform.getItem("u_dwsx").getValue()
                    },
                    function (res) {
                        console.log(res, 'resgetHsdjToYztj')
                    }
                );

            }

            if (row.u_wl_name) {
                //功能扩展
                $NG.execServer(
                    "getItemdataphid",
                    { phid: row.u_wl_name },
                    function (res) {
                        const data = JSON.parse(res.data)[0].extendObjects; //单返回值
                        $NG.execServer(
                            "getItemdataByPhid",
                            { phid: data.phid_itemdata },
                            function (res) {
                                const datas = JSON.parse(res.data)[0].extendObjects; //单返回值
                                row.u_gg = datas.spec;
                                row.u_jldw = datas.msunit_name;
                                row.u_wl_no = datas.itemno;
                                console.log(datas); //物料小类
                                console.log(datas.phid_resbs); //物料小类
                            }
                        );
                    }
                );
                $NG.execServer("getResKSeach", { item_phid: row.u_wl_name }).then(
                    (res) => {
                        if (!res.data.length > 0) return; //判断是否有数据
                        const data = JSON.parse(res.data)[0].extendObjects; //单返回值
                        console.log(data.hsprc, "data.hsprc");
                        if (data.hsprc === 0) {
                            console.error("市场价格不能为 0，否则会导致除数为 0 的错误。");
                        } else {
                            row.u_sc_prc = data.hsprc;
                        }
                        let result = calculateLossRate(row.u_vat_prc, row.u_sc_prc);
                        console.log(result, "11111");
                        row.u_ssl = result;
                        grid1.refreshView();
                    },
                    (error) => {
                        console.log(error);
                    }
                );
            }
            // 根据物料编码带出信息
            if (row.u_wl_no_EXName) {
                $NG.execServer(
                    "getItemdataByNo",
                    { itemno: "'" + row.u_wl_no_EXName + "'" },
                    function (res) {
                        if (res.count > 0) {
                            let requestData = JSON.parse(res.data)[0].extendObjects; //单返回值
                            console.log(requestData, "获取请求值");
                            //物料名称
                            row.u_wl_name = requestData.itemname;
                            //物料编码
                            row.u_wl_no = requestData.phid;
                            row.u_wl_no_EXName = requestData.itemno;
                            //规格
                            row.u_gg = requestData.spec;
                            //计量单位
                            row.u_jldw = requestData.msunit_name;
                            // row.u_jldw = requestData.msunit_phid;
                            // row.u_jldw_EXName = requestData.msunit_name; //单位
                            //物料分类
                            row.u_product_type_mini = requestData.phid_resbs; //单位
                            row.u_product_type_mini_EXName = requestData.name; //单位
                            if (row.u_product_type_mini) {
                                $NG.execServer(
                                    "getAutoType",
                                    { phid: row.u_product_type_mini },
                                    function (res) {
                                        const datas = JSON.parse(res.data)[0].extendObjects; //单返回值
                                        row.u_item_sort = datas.f_phid;
                                        row.u_item_sort_EXName = datas.fname;
                                        row.u_product_type = datas.g_phid;
                                        row.u_product_type_EXName = datas.gname;
                                        row.u_product_type_mini = datas.phid_resbs;
                                        row.u_product_type_mini_EXName = datas.name;
                                        grid1.refreshView();
                                    }
                                );
                            }
                            grid1.refreshView();
                        } else {
                            console.log("useUpdateRows没有找到拟采购清单"); // items.u_u_pur_item = null; // items.u_u_pur_item_EXName = null;
                        }
                    }
                );
            }
            if (row.u_product_type_mini) {
                $NG.execServer(
                    "getAutoType",
                    { phid: row.u_product_type_mini },
                    function (res) {
                        const datas = JSON.parse(res.data)[0].extendObjects; //单返回值
                        row.u_item_sort = datas.f_phid;
                        row.u_item_sort_EXName = datas.fname;
                        row.u_product_type = datas.g_phid;
                        row.u_product_type_EXName = datas.gname;
                        row.u_product_type_mini = datas.phid_resbs;
                        row.u_product_type_mini_EXName = datas.name;
                        grid1.refreshView();
                    }
                );
            }
            grid1.refreshView()
        });
    }, "p_form_owner_rec_apply_d1");
    //页面条件
    if (page.oType == "add") {
        mstform.getItem("ng_insert_dt").setValue(new Date());
    }
});
function calculateLossRate(taxIncludedPrice = 0, marketPrice) {
    let lossRate =
        (Number(taxIncludedPrice) - Number(marketPrice)) / Number(marketPrice);
    return lossRate;
}


function TYBZSJH(setProps,onWindow){
    
const style = document.createElement("style"); // 创建一个新的 <style> 元素
const cssRules = `
 
        .zdy-bigBox{
            background:white;
            width: 60vw;
            height:60vh;
            top:15vh;
            left:20vw;
            border-radius:4px;
        }
        .zdy-tableHeader{
            border-bottom:1px #d3d3d3 solid;
            padding:1vh 0 ;
            display:flex;
            justify-content: space-between;
        }
        .zdy-header-button{
            width:35%;
        }
        .zdy-header-button input{
            border:1px #d3d3d3 solid;
            border-radius: 4px;
            height:100%;
            width:80%;
            font-size:40%;
            outline: none;
            padding-left:2px;
        }
        .zdy-header-button button{
            width:2vw;
            height:2vw;
        }
        .zdy-title{
            border-left:4px #1677ff solid;
            padding:0 0 0 0.5vw ;
        }
        .header{
            display:flex;
        }
        /* tabs */
        .zdy-tabs-box{
            width:100%;
            height:8%;
            border:1px green solid;
        }
        .zdy-tabs-box ul{
            width:auto;
            height:100%;
            padding-left:2%;
            display:flex;
            list-style: none;
            font-size:90%;
            align-items:end;
        }
        .zdy-tabs-box li{
            height:auto;
            margin-right:10%;
            border-bottom:#1677ff solid 2px;
        }
        .zdy-table{
            width:100%;
            border-collapse: collapse;
            overflow:hidden;
            text-align:left;
            background:#fff;
        }
        .zdy-table-box{
            margin:1% auto;
            width:98%;
            height:80%;
            overflow-y:scroll;
        }
        .zdy-table tr{
            height: 30px;
            border-bottom:1px #d0d0d0 solid;
            /*border:1px black solid;*/
            transition: all 0.2s linear;
        }
        .zdy-table td,.zdy-table th{
            padding:1.5% 0;
            /*border:1px black solid;*/
        }
        .zdy-table-thead-tr,zdy-table-tbody-tr{
            vertical-align: top;
        }
        .zdy-table-thead-tr th{
            height:10px;
        }
        .zdy-col-box{
            width:100%;
            display:none;
            height:5%;
            ul{
                list-style: none;
                display:flex;
            }
        }
        .zdy-box-page{
            width:100%;
            display:flex;
        }
        .zdy-btn-ok{
            width:100%;
            height:5%;
            display:flex;
            justify-content: end;
        }
        .zdy-btn-ok button{
            margin-right:5%;
            width:6vw;
        }
        .zdy-btn-box{
            display:flex;
        }
            .zdy-active{
            background-color: hsl(215, 100%, 94%);
        }
            #zdy-main{
                background:#0000007a;
                width:100%;
                height:100vh;
                position:fixed;
                top:0;
                left:0;
                z-index:999;
                display:none;
                justify-content: center;
                align-items:center
            }
`;
style.textContent = cssRules; // 设置 <style> 元素的内容为CSS规则字符串
document.head.appendChild(style);

TestBody();
ajaxGet();
//关闭
function offT() {
  document.querySelector("#zdy-main").style.display = `none`;
}
//开启
function onT() {
  document.querySelector("#zdy-main").style.display = `flex`;
}
function TestBody() {
  let code = `
        <div id="zdy-main">
            <div class="zdy-bigBox" >
        <!-- 表头 start -->
        <div class="zdy-tableHeader">
            <h5 class="zdy-title">商机信息</h5>
            <div class="zdy-header-button">
                <input type="text" placeholder="请输入关键词">
                <button id="X">X</button>
            </div>
        </div>
        <!-- 表头 end -->

        <!-- Tabs start -->
         <div class="zdy-col-box">
            <ul>
                <li>所有数据</li>
            </ul>
         </div>
         <!-- Tabs end -->

         <!-- 表体 start -->
          <div class="zdy-table-box">
              <table class="zdy-table" id="zdy-table">
                
                  
              </table>
          </div>
         <!-- 表体 end -->
<!--        分页控件 start-->
        <div class="zdy-col-box">
            <p>第1-20条/总共 70条</p>
            <div class="zdy-box-page">
                <button><</button>
                <ul>
                    <li>1</li>
                    <li>2</li>
                    <li>3</li>
                    <li>4</li>
                </ul>
                <button>></button>
            </div>
        </div>
        <!--        分页控件 end-->
        <div class="zdy-btn-ok">
           <div class="zdy-btn-box">
               <button id="zdy-btn-off">取消</button>
               <button id="zdy-btn-on">确定</button>
           </div>
        </div>
    </div>
        </div>
    `;
  document.querySelector("#root").insertAdjacentHTML("beforeend", code);
  document.querySelector("#zdy-btn-off").addEventListener("click", (e) => {
    offT();
    if (!nodeActive) return;
    nodeActive.classList.remove("zdy-active");
    currentSeleRow = -1;
  });
  document.querySelector("#X").addEventListener("click", (e) => {
    offT();
    if (!nodeActive) return;
    nodeActive.classList.remove("zdy-active");
    currentSeleRow = -1;
  });
  //TODO 缺少字段
  document.querySelector("#zdy-btn-on").addEventListener("click", (e) => {
    console.log(resData[currentSeleRow]);
    const _data = resData[currentSeleRow];
    if (currentSeleRow !== -1) {
      $NG.updateState((updater) => {
        updater.data.p_form_integrated_apply_m.setProps({
          u_bus_no: _data.ProjectNo__c,
          u_sj_name: _data.name,
          u_tar_amt: _data.field_3blb1__c,
        });
      });
    }
    nodeActive.classList.remove("zdy-active");
    currentSeleRow = -1;
    offT();
  });
}
// 请求服务器
function ajaxGet() {
  const mstform = $NG.getCmpApi("p_form_integrated_apply_m");
  console.log("调用ajaxGet");
  if (!mstform.getItem("u_pc_pre_sales").getValue()) {
    let str = `
            <h4>获取帮助失败，请重新选择售前</h4>
    `;
    document.querySelector("#zdy-table").innerHTML = str;
    return;
  }
  $NG.execServer("getBusNo", { phid: mstform.getItem("u_pc_pre_sales").getValue() }, (res) => {
    try {
      //#region
      console.log(`查找编码`, res);
      if (res.count == 0) {
        let str = `
            <h4>当前项目售前字段数据存在问题，可能是没编码！</h4>
    `;
        document.querySelector("#zdy-table").innerHTML = str;
      }
      const _data = JSON.parse(res.data)[0].extendObjects;
      //发请求
      const xhr = new XMLHttpRequest();
      xhr.open("POST", "http://nginx.clouddev.hisense.com/sd/sdToCrm/apply/opportunity/query");
      xhr.setRequestHeader("Content-Type", "application/json");
      xhr.send(
        JSON.stringify({
          name: String(_data.bill_no),
        })
      );
      let str = `
     <thead>
        <tr class="zdy-table-thead-tr">
            <th>商机编码</th>
            <th>商机名称</th>
            <th>项目金额</th>
            <th>预计签单时间</th>
        </tr>
    </thead>
    <tbody>
    `;
      xhr.onreadystatechange = function () {
        if (xhr.readyState === 4 && xhr.status === 200) {
          var response = JSON.parse(xhr.responseText);
          console.log("服务器端返回的响应:", response);
          if (response.length == 0) {
            str = `
            <h4>当前项目售前无数据</h4>
    `;
            document.querySelector("#zdy-table").innerHTML = str;
            return;
          }
          resData = response;
          resData.forEach((item) => {
            str += `
                     <tr class="zdy-table-tbody-tr">
                        <td>${item.ProjectNo__c}</td>
                        <td>${item.name}</td>
                        <td>${item.field_3blb1__c}</td>
                        <td>${item.expected_signing_time_text__c}</td>
                    </tr>
                `;
          });
          str += "</tbody></table>";
          // document.querySelector("#zdy-table").addEventListener
          document.querySelector("#zdy-table").insertAdjacentHTML("beforeend", str);
          if (domTRarr) {
            domTRarr.forEach((item) => {
              item.removeEventListener("click", itemFC());
            });
          }
          domTRarr = document.querySelectorAll(".zdy-table-tbody-tr");
          domTRarr.forEach((item, index) => {
            item.addEventListener("click", (e) => {
              itemFC(e, index);
            });
            item.addEventListener("dblclick", () => {
              console.log(`双击事件`);
              dbClick();
            });
          });
        } else {
          console.log(`状态`, xhr.readyState);
        }
      };
      //#endregion
    } catch (error) {
      console.log(error);
    }
  });

  //双击触发事件
  function dbClick() {
    const _data = resData[currentSeleRow];
    currentSeleRow = -1;
    document.querySelector("#zdy-main").style.display = `none`;
    try {
      nodeActive.classList.remove("zdy-active");
    } catch (e) {}
    $NG.updateState((updater) => {
      updater.data.p_form_integrated_apply_m.setProps({
        u_bus_no: _data.ProjectNo__c,
        u_sj_name: _data.name,
      });
    });
  }
  // 点击逻辑
  function itemFC(e, index) {
    currentSeleRow = index;
    console.log(e, "qf");
    if (e.target instanceof HTMLTableCellElement) {
      const pre = e.target.parentNode;
      if (pre instanceof HTMLTableRowElement) {
        if (nodeActive) {
          nodeActive.classList.remove("zdy-active");
        }
        nodeActive = pre;
        nodeActive.classList.add("zdy-active");
      }
    }
  }
}
}
